package com.xiashitech.agent.instrumentation.spring.security.inst;

import com.xiashitech.agent.cache.status.CacheStatus;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.bridge.Java8Bridge;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.agent.utils.DurationPrinter;
import com.xiashitech.agent.utils.XSUtil;
import io.opentelemetry.javaagent.bootstrap.CallDepth;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Scope;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

import java.util.Date;

import static com.xiashitech.agent.instrumentation.spring.security.XSSpringSecuritySingletons.instrumenter;
import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.takesArgument;

public class XSSecurityContextHolderInstrumentation implements TypeInstrumentation {
    @Override
    public ElementMatcher<TypeDescription> typeMatcher() {
        return named("org.springframework.security.core.context.SecurityContextHolder");
    }

    @Override
    public void transform(TypeTransformer transformer) {
        transformer.applyAdviceToMethod(named("setContext")
                .and(takesArgument(0, named("org.springframework.security.core.context.SecurityContext"))),
                XSSecurityContextHolderInstrumentation.class.getName() + "$XSContextHolderAdvice");
    }
    public static class XSContextHolderAdvice {

        @Advice.OnMethodEnter(suppress = Throwable.class)
        public static void onEnter(
                @Advice.Argument(0) Object securityContext,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
            DurationPrinter durationPrinter = new DurationPrinter("XSSecurityContextHolderInstrumentation");
            if (CacheStatus.cannotRun()) {
                return;
            }
            if (XSUtil.isNotEmpty(Java8Bridge.currentForBaggage().getEntryValue("xs.userId"))){
                return;
            }
            try {
                Context parentContext = currentContext();
                if (instrumenter().shouldStart(parentContext, null)) {
                    parentContext = BaggageUtil.syncBaggage().build().storeInContext(parentContext);
                    context = instrumenter().start(parentContext, null);
                    context = BaggageUtil.syncBaggage().build().storeInContext(context);
                    scope = context.makeCurrent();

                    scope.close();
                    UserRequest userRequest = UserRequest.builder()
                            .requestDate(String.valueOf(new Date().getTime()))
                            .loginRequest(Boolean.TRUE)
                            .build();
                    instrumenter().end(context, userRequest, securityContext,null);
                }
            } catch (Throwable e) {
                StartConfig.throwableStackPrinter(e);
            }
            durationPrinter.printElapseDuration("XSContextHolderAdvice b");
        }
    }
}
